#include "Printer.h"
#include "LinkedList.h"

#include <iostream>
#include <iomanip>
#include <sstream>

using std::dec;
using std::left;
using std::right;
using std::setw;
using std::stringstream;
using std::endl;
using std::cout;

void Printer::checkPrint(int& line, int& page, string& file, string& date) const
{
	if(!(line % PAGE_LENGTH))
	{
		cout << "Page " << 
			dec << right << setw(4) << page << " " <<
			file << " " <<
			date << endl << endl;
		++page;
		line += 3;
	}
	++line;
}

Printer::Printer(Scanner& in)
{
	static const int PAGE_LENGTH = 50;
	int line = 0;
	int page = 1;
	int src_line = 1;
	string file = in.getSourceFileName();

	time_t timer;
	time(&timer);
	string date = asctime(localtime(&timer));

	in.getLines()->for_each([&](SourceLine* in){
		checkPrint(line, page, file, date);
		cout << right << setw(4) << src_line << ": " << in->getSourceLine() << endl;
		++line;
		++src_line;

		in->getTokens()->for_each([&](Token* in){
			checkPrint(line, page, file, date);
			cout << "    >> " << left << setw(17) << in->printType() << in->print() << endl;
		});
	});

	cout << "Cross Reference Information" << endl;
	cout << "Identifier         Line Numbers" << endl;
	cout << "-----------        ------------" << endl;
	in.getIdentifiers()->for_each([](IdentifierGroup* in){
		cout << left << setw(19) << in->getIdentifierName();
		int i = 0;
		in->getLineNumbers()->for_each([&i](int in){
			if(i++) cout << "\t";
			cout << in;
		});
		cout << endl;
	});
}
